#!usr/bin/python3
#-*-coding:utf-8-*-
import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
import json

class WebSockrtHandler(tornado.websocket.WebSocketHandler):
  user = []
  userName = {}
  def check_origin(self,origin):
    return True
  def open(self):
    print('正在连接.....')
    self.user.append(self)
    #发送在线列表给打开客户端的人
    userNameList = self.userName.values()
    
    returnMsgS = {}
    returnMsgS['type'] = 'group'
    returnMsgS['code'] = '200'
    returnMsgS['title'] = ''
    returnMsgS['text'] = list(userNameList)
    returnMsgS = json.dumps(returnMsgS)
    self.sendMessageSelf(returnMsgS)

  def on_message(self,message):
    returnMsg = {}
    try:
      message = json.loads(message)
      ##tip与alter均为创建名字时使用,信息为message,其他错误用danger
      if message['type'] == 'name':
        if not self in self.userName:
          userNameList = self.userName.values()
          if not message['text'] in userNameList:
            self.userName[self] = message['text']
            returnMsg['type'] = 'tip'
            returnMsg['code'] = '200'
            returnMsg['title'] = ''
            returnMsg['text'] = '{0}加入聊天室'.format(message['text']) 
            
            #发送消息给自己
            returnMsgS = {}
            returnMsgS['type'] = 'self'
            returnMsgS['code'] = '200'
            returnMsgS['title'] = ''
            returnMsgS['text'] = ''
            returnMsgS = json.dumps(returnMsgS)
            self.sendMessageSelf(returnMsgS)

            #发送信息给全部人
            returnMsgA = {}
            returnMsgA['type'] = 'group'
            returnMsgA['code'] = '200'
            returnMsgA['title'] = ''
            returnMsgA['text'] = list(userNameList)
            returnMsgA = json.dumps(returnMsgA)
            self.sendMessageAll(returnMsgA,self.user)
          else:
            returnMsgS = {}
            returnMsgS['type'] = 'alter'
            returnMsgS['code'] = '300'
            returnMsgS['title'] = ''
            returnMsgS['text'] = '名字已存在'
            returnMsgS = json.dumps(returnMsgS)
            self.sendMessageSelf(returnMsgS)
        else:
          returnMsgS = {}
          returnMsgS['type'] = 'alter'
          returnMsgS['code'] = '300'
          returnMsgS['title'] = ''
          returnMsgS['text'] = '你已在聊天室中，名字为{0}'.format(self.userName[self])  
          returnMsgS = json.dumps(returnMsgS)
          self.sendMessageSelf(returnMsgS)
      else:
        if self in self.userName:
          #反馈信息给发送者
          returnMsgS = {}
          returnMsgS['type'] = 'selfM'
          returnMsgS['code'] = '200'
          returnMsgS['title'] = ''
          returnMsgS['text'] = ''
          returnMsgS['id'] = message['id'] 
          returnMsgS = json.dumps(returnMsgS)
          self.sendMessageSelf(returnMsgS)
          #发送信息给其他人
          returnMsg['type'] = 'message'
          returnMsg['code'] = '200'
          returnMsg['title'] = self.userName[self]
          returnMsg['text'] = message['text']
        else:
          returnMsgS = {}
          returnMsgS['type'] = 'alter'
          returnMsgS['code'] = '300'
          returnMsgS['title'] = ''
          returnMsgS['text'] = '你还没加入聊天室'
          returnMsgS = json.dumps(returnMsgS)
          self.sendMessageSelf(returnMsgS)

      if returnMsg:
        returnMsg = json.dumps(returnMsg)
        self.sendMessageOther(returnMsg,self.user)
      
    except Exception as e:
      print(e)
      # exit()
  def on_close(self):
    if self in self.user:
      self.user.remove(self)
    if self in self.userName:
      self.userName.pop(self)
    userNameList = self.userName.values()
    #发送信息给全部人
    returnMsgA = {}
    returnMsgA['type'] = 'group'
    returnMsgA['code'] = '200'
    returnMsgA['title'] = ''
    returnMsgA['text'] = list(userNameList)
    returnMsgA = json.dumps(returnMsgA)
    self.sendMessageAll(returnMsgA,self.user)
    print('连接断开.....')
  
  #发送信息给其他人
  def sendMessageOther(self,msg,user):
    for client in user:
      try:
        if client is self:
          continue
        client.write_message(msg)
      except Exception as e:
        pass
  
  #发送信息给自己
  def sendMessageSelf(self,msg):
    self.write_message(msg)

  #发送信息给全部人
  def sendMessageAll(self,msg,user):
    for client in user:
      try:
        client.write_message(msg)
      except Exception as e:
        pass

class Application(tornado.web.Application):
  def __init__(self):
    handlers = [
      (r'/ws',WebSockrtHandler)
    ]
    settings = {
      'template_path':'static'
    }
    tornado.web.Application.__init__(self,handlers,**settings)

if __name__ == '__main__':
  ws_app = Application()
  server = tornado.httpserver.HTTPServer(ws_app)
  server.listen(8090)
  tornado.ioloop.IOLoop.instance().start()


